package com.spider.site.dao.base;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;
/**
 * 数据库操作基类
 * @author wq
 *
 * @param <T>
 */
@Repository
@Transactional
public class BaseDao<T> {

	@PersistenceContext
	protected EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	public List<T> getAll(T entity){
		final String hql = " FROM " + entity.getClass().getName();
		return this.entityManager.createQuery(hql).getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public T get(Serializable id , T entity) {
		return (T) this.entityManager.find(entity.getClass(), id);
	}
	
	public boolean save(T entity) {
		try {
			this.entityManager.persist(entity);
			return true;
		} catch (Exception e) {
			System.out.println(e);
			return false;
		}
	}
	
	public boolean update(T entity) {
		try {
			this.entityManager.merge(entity);
			return true;
		} catch (Exception e) {
			System.out.println(e);
			return false;
		}
	}

	public boolean delete(T entity) {
		try {
			this.entityManager.remove(entity);
			return true;
		} catch (Exception e) {
			System.out.println(e);
			return false;
		}
	}
	
}
